{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install geopy"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import requests\n",
    "from geopy.geocoders import Nominatim\n",
    "\n",
    "def get_location():\n",
    "    try:\n",
    "        # Fetch location data from ip-api\n",
    "        ip_url = 'http://ip-api.com/json/'\n",
    "        response = requests.get(ip_url)\n",
    "        data = response.json()\n",
    "\n",
    "        # Check if the response is successful\n",
    "        if data['status'] == 'success':\n",
    "            latitude = data['lat']\n",
    "            longitude = data['lon']\n",
    "\n",
    "            # Use geopy to get more detailed location data\n",
    "            geolocator = Nominatim(user_agent=\"geoapiExercises\")\n",
    "            location = geolocator.reverse(f\"{latitude}, {longitude}\", exactly_one=True)\n",
    "            if location:\n",
    "                return location.latitude, location.longitude\n",
    "            else:\n",
    "                return latitude, longitude\n",
    "        else:\n",
    "            return \"Location could not be determined using IP.\", \"\"\n",
    "\n",
    "    except Exception as e:\n",
    "        return f\"An error occurred: {e}\", \"\"\n",
    "\n",
    "latitude, longitude = get_location()\n",
    "if latitude and longitude:\n",
    "    print(f\"Current Latitude: {latitude}\")\n",
    "    print(f\"Current Longitude: {longitude}\")\n",
    "else:\n",
    "    print(latitude)  # This would print the error message if location could not be determined\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
